﻿using DevExpress.XtraLayout;
using DevExpress.XtraReports.Parameters;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace MESQWinform
{
    /// <summary>
    /// HTTP请求方法枚举
    /// </summary>
    public enum HttpMethod
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    /// <summary>
    /// API客户端工具类，提供HTTP请求方法
    /// </summary>
    public static class APIClientl
    {
        private static readonly HttpClient client = new HttpClient();
        private static readonly string baseUrl = "http://47.110.243.157:5052/";

        /// <summary>
        /// 构建完整URL
        /// </summary>
        private static string BuildUrl(string relativeUrl)
        {
            string url = baseUrl.TrimEnd('/') + "/" + relativeUrl.TrimStart('/');
            
            // 如果是分页查询，自动添加需要返回总记录数的参数
            if (url.Contains("pageindex=") && url.Contains("pagesize=") && !url.Contains("includeTotalCount="))
            {
                url += url.Contains("?") ? "&includeTotalCount=true" : "?includeTotalCount=true";
            }
            
            return url;
        }

        /// <summary>
        /// 统一处理API响应
        /// </summary>
        private static async Task<string> ProcessResponseAsync(HttpResponseMessage response)
        {
            try
            {
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                throw new Exception($"API响应处理失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 通用API调用方法
        /// </summary>
        /// <param name="relativeUrl">相对路径，如"api/Shelves/GetShelves"</param>
        /// <param name="method">请求方式：GET、POST、PUT或DELETE</param>
        /// <param name="postData">POST/PUT请求时的json数据，其他方法可为null</param>
        /// <returns>接口返回的字符串</returns>
        public static async Task<string> CallApiAsync(string relativeUrl, string method = "GET", string postData = null)
        {
            string url = BuildUrl(relativeUrl);
            
            try
            {
                HttpResponseMessage response;
                
                switch (method.ToUpper())
                {
                    case "GET":
                        response = await client.GetAsync(url);
                        break;
                    case "POST":
                        var content = new StringContent(postData ?? "", Encoding.UTF8, "application/json");
                        response = await client.PostAsync(url, content);
                        break;
                    case "PUT":
                        var putContent = string.IsNullOrEmpty(postData) ? null : 
                            new StringContent(postData, Encoding.UTF8, "application/json");
                        response = await client.PutAsync(url, putContent);
                        break;
                    case "DELETE":
                        response = await client.DeleteAsync(url);
                        break;
                    default:
                        throw new NotSupportedException($"不支持的请求方式: {method}");
                }
                
                return await ProcessResponseAsync(response);
            }
            catch (Exception ex)
            {
                throw new Exception($"调用API失败: {ex.Message}", ex);
            }
        }
        
        /// <summary>
        /// 通用API调用方法（使用枚举类型的HTTP方法）
        /// </summary>
        /// <param name="relativeUrl">相对路径，如"api/Shelves/GetShelves"</param>
        /// <param name="method">请求方式枚举</param>
        /// <param name="postData">POST/PUT请求时的json数据，其他方法可为null</param>
        /// <returns>接口返回的字符串</returns>
        public static async Task<string> CallApiAsync(string relativeUrl, HttpMethod method, string postData = null)
        {
            string methodStr = method.ToString();
            return await CallApiAsync(relativeUrl, methodStr, postData);
        }
        
        /// <summary>
        /// 兼容旧版本的API调用方法
        /// </summary>
        /// <param name="relativeUrl">相对路径，如"api/Shelves/GetShelves"</param>
        /// <param name="method">请求方式：GET或POST</param>
        /// <param name="postData">POST时的json字符串，GET时可为null</param>
        /// <returns>接口返回的字符串</returns>
        public static async Task<string> CallApiAsyncl(string relativeUrl, string method = "GET", string postData = null)
        {
            return await CallApiAsync(relativeUrl, method, postData);
        }
        
        /// <summary>
        /// 发送DELETE或PUT请求的API调用方法
        /// </summary>
        /// <param name="relativeUrl">相对路径，如"api/WorkShop/DeleteWorkShop?id=2"</param>
        /// <param name="method">请求方式：PUT或DELETE</param>
        /// <returns>接口返回的字符串</returns>
        public static async Task<string> DeleteApiAsync(string relativeUrl, string method = "PUT")
        {
            return await CallApiAsync(relativeUrl, method);
        }
    }
}
